package org.webbase.system.dao.file;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;
import org.webbase.common.util.FileUtil;
import org.webbase.system.dao.JournalDao;
import org.webbase.system.pojo.Journal;
@Repository
public class JournalDaoImpl implements JournalDao {

	private static final String logPath = "E:/webbase/logs";
	private static final String logBackPath = "E:/webbase/logs/backup/";
	
	@Override
	public List<Journal> query(String logLevel, String logDate) {
		// TODO Auto-generated method stub
		List<File> todayLog = new ArrayList<File>();				// 获取当天的日志文件
		List<File> monthLog = new ArrayList<File>();				// 获取 logDate 这个月的日志文件
		List<Journal> returnList = new ArrayList<Journal>();		// 获取 logDate 这个月的日志文件信息
		StringBuilder sb = new StringBuilder();						// 组装文件名称关键字
		StringBuilder sblogBackPath = new StringBuilder();			// 组装文件需要获取文件的路径
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");		// 日期格式
		Date date = new Date();										// 当前日期
		String month = sdf.format(date);							// 格式化当前日期
		sb.append(logLevel);			
		sb.append(".");
		sb.append(logDate);
		sblogBackPath.append(logBackPath);
		sblogBackPath.append(logDate);
		if(month.equals(logDate)){									// 判断当前日期是否与要查询的日期一至
			todayLog = FileUtil.getFile( logPath, 1, logLevel);
		}
		monthLog = FileUtil.getFile(sblogBackPath.toString(), 1,sb.toString());
		monthLog.addAll(todayLog);
		for (File file : monthLog) {
			returnList.add(new Journal(file));
		}
		return returnList;
	}

	
	@Override
	public String check(String logLevel, String logDate) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		String today = sdf.format(date);
		StringBuilder filePath = new StringBuilder();
		// 组装文件需要读取的路径
		if(logDate.equals(today)){
			filePath.append(logPath);
			filePath.append("/");
			filePath.append(logLevel);
			filePath.append(".log");
		}else{
			filePath.append(logBackPath);
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM");
			try {
				Date dateLog = sdf2.parse(logDate);
				filePath.append(sdf2.format(dateLog));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			filePath.append("/");
			filePath.append(logLevel);
			filePath.append(".");
			filePath.append(logDate);
			filePath.append(".log");
		}
		return FileUtil.readFileByLinesShowInHtml(filePath.toString());
	}

}
